<template>
	<view>
		<view class="invoice-header">
			<tabs ref="tabsRef" :list="tablist" :current="tabCur" @tabItemClick="tabSelect" marright="60rpx"
				activeWeight='700' fontSize="32rpx" activeColor="#333" barMargin="8" activeBarColor="#53A87F">
			</tabs>
		</view>
		<view class="invoice-con">
			<view class="invoice-li flex justify-between align-center">
				<view class="invoice-li-tile" @click="showPop('propTime')">
					<picker class="padding-tb-sm piont" mode="date" :value="date" @change="bindDateChange" fields="month">
						<view class="uni-input">{{timeName}}<text class="lg text-gray cuIcon-unfold"></text></view>
					</picker>
				</view>
				<view class="invoice-li-operation padding-tb-sm piont" @click="operationFn" v-if="tabCur==0||tabCur==2"
					:class="{operationActive:operation}">批量发送</view>
			</view>
			<view class="inv-list">
				<empty positions="absolute" :empty="loadedList&&menuList.length<=0" :zIndexs="100"
					:imgUrl="'https://cdn-static.yekjx.com/'+'food/empty/images/empty_ico04.png'" :content="tabCur==0?'暂无开票记录':(tabCur==1?'暂无开票中记录':(tabCur==2?'暂无已开票记录':'暂无开票记录'))"></empty>
				<scroll-view class="uni-bar-wbg" style="height:100%" scroll-y scroll-with-animation refresher-enabled="true"
					:refresher-triggered="refLoad" @refresherrefresh="refresherrefresh" @scrolltolower="scrolltolower">
					<view class="invoice-li invoice-li-flex flex align-center piont" v-for="(item,index) in menuList" :key="index"
						@click="tapItem(item)">
						<view class="invoice-li-left" v-if="operation">
							<text class="text-xll margin-right-xs" :class="item.select?'cuIcon-roundcheckfill':'cuIcon-round'"></text>
						</view>
						<view class="invoice-li-right flex flex-direction">
							<view class="flex justify-between invoice-li-li invoice-li-li-font">
								<view class="flex justify-between">
									<view class="invoice-log-bg" :class="{operationActiveBg:item.state == '1'&&operation}"><text
											class="color-style" :class="item.logo"></text></view>
									<tetx :class="{operationActive:item.state == '1'&&operation}">{{item.numberName.length>14?item.numberName.substring(3):item.numberName}}</tetx>
								</view>
								<view class="text-c9">{{ item.state =='2' ? '已开票' : '商家开票中' }}</view>
							</view>
							<view class="flex justify-between invoice-li-btm-font">
								<text>{{ item.validity }}</text>
								<text class="invoice-li-btm-fontWei"
									:class="{operationActive:item.state =='2'&&operation}">￥{{item.inv_money}}</text>
							</view>
						</view>
					</view>
					<view class="flex justify-center">
						<uni-load-more :status="loadStatus" iconType="circle"></uni-load-more>
					</view>
				</scroll-view>
			</view>
			<!-- <view class="prompt flex justify-center align-center">
				仅支持3个月内的订单开具发票
			</view> -->
		</view>
		<view class="invoice-footer" v-if="operation">
			<view class="footer-left" @click="allSecle">
				<text class="text-xll margin-right-xs" :class="select?'cuIcon-roundcheckfill':'cuIcon-round'"></text>
				<text class="f-font-style">全选</text>
			</view>
			<view class="footer-center">
				<text class="f-font-style">已选{{selectNums.nums}}张</text>
				<text class="f-font-stylecon">共¥ <text class="f-font-style3">{{selectNums.moneys.toFixed(2)}}</text></text>
			</view>
			<view class="footer-right" @click="sendtoEmail">
				<text>发送到邮箱</text>
			</view>
		</view>

		<uni-popup ref="popupEmil" class="uni-propun-con" :safeArea="false">
			<view class="popup-content">
				<view class="uni-dialogCon">
					<view class="belivery-title">发送到邮箱</view>
					<view class="popupEmil-input">
						<input type="text" v-model="popupEmilvalue" placeholder="请输入邮箱地址" placeholder-class="popupEmilInput" />
					</view>
					<view class="tipss">预计3个工作日内通过邮箱送达</view> 
					<view class="popupEmil-btn flex justify-between align-center">
						<view @click="hidePop('popupEmil')">取消</view>
						<view @click="submitSend">发送</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed } from 'vue'
	import { onShow, onLoad } from '@dcloudio/uni-app';
	import tabs from '@/components/comtabs/comtabs.vue'
	import { showLoading, hideLoading, mnavTo } from '@/utils/helper';
	import { queryInvoice, batchInvoice } from '@/api/vmeitime-http/index.js'
  import mApi from "@/utils/mapi";
	const tabsRef = ref()  //订单列表
	const tabCur = ref(0) //订单列表
	const operation = ref(false) //操作
	const select = ref(null)
	const popupEmil = ref(null) //发生邮箱
	const propTime = ref(null)
	const refLoad = ref(false)
	const popupEmilvalue = ref()
	const loadedList = ref(false)//是否加载
	const loadStatus = ref('noMore')
	const nowChangeState = ref("")
	const postTimes=ref("")
	const loaded=ref(false)
	const pageInfo = ref({
		curPage: 1,
		pageSize: 10,
		backCupPage: 2
	})
	const tablist = ref([
		{
			orderState: "",
			name: "全部"
		}, {
			orderState: "1146",
			name: "开票中"
		}, {
			orderState: "1147",
			name: "已开票"
		}
	])
	const menuList = ref<any>([])
	const date = ref('')
	const timeName = ref('')
	onLoad(() => {
		
	})
	onShow(()=>{
		const now = new Date();
		const year = now.getFullYear();
		const month = now.getMonth() + 1; // getMonth() 返回值范围是 0-11，所以需要加 1
		const formattedDate = `${year}-${month}-11`;
		date.value=formattedDate
		bindDateChange({ detail: { value: formattedDate } })
		nowChangeState.value = ""
	})
	const bindDateChange = (e:any) => {
		date.value = e.detail.value+'-11'
		let time = e.detail.value.split('-')
		timeName.value = time[0] + '年' + parseInt(time[1]) + '月'
		postTimes.value=time[0]+time[1].toString().padStart(2, '0')
		loadList('refeash')
	}
	const loadList = async (source : any) => {
		loadStatus.value = 'loading'
		loadedList.value = true
		
		if (source == 'refeash') {
			pageInfo.value.curPage = 1
			pageInfo.value.backCupPage = 2
		}
		if (pageInfo.value.curPage > pageInfo.value.backCupPage && source != 'refeash') {
			console.log("没有更多啦")
			loadStatus.value = 'noMore'
			return
		}
		// showLoading()
		try {
			let res = await queryInvoice({ curPage: pageInfo.value.curPage, pageSize: pageInfo.value.pageSize,status:nowChangeState.value,create_date:postTimes.value })
			
			if (!res.result) {
				// if (res.shortMessage == '用户未登录') {
				// 	mnavTo('/pages/login/login')
				// }
				hideLoading()
				return
			}
			hideLoading()
			if (source == 'refeash') {
				menuList.value = []
			}
			if(res.object.length==0){
				loadStatus.value = 'noMore'
				return
			}
			if (res.page.curPage == res.page.nextPage) {
				loadStatus.value = 'noMore'
			} else {
				loadStatus.value = 'more'
			}
			pageInfo.value.curPage += 1
			pageInfo.value.backCupPage = res.page.totalPage || 0
		
			for (let item of res.object) {
				menuList.value.push({
					...item,
					select: false,
					logo: 'fcon-logo',
					state: item.status == '1147' ? '2' : '1',
					validity: `${item.create_date.slice(0, 4)}-${item.create_date.slice(4, 6)}-${item.create_date.slice(6, 8)}` + " " + item.create_date.slice(8, 10) + ":" + item.create_date.slice(10, 12) + ":" + item.create_date.slice(12, 14),
				})
			}
		} catch (e) {
			loadedList.value = true
			//TODO handle the exception
			loadStatus.value = 'noMore'
		}


	}
  const selectNums = computed(() => {
		let nums=0;
		let moneys=0
		menuList.value.forEach(item => {
			if(item.select){
				nums+=1
				moneys+=item.inv_money
			}
		})
		return {
			nums,
			moneys
		}
	})
	const tapItem = async(item : any) => {
		if (operation.value && item.state == 2) {
			item.select = !item.select
		}

		let selectAll = menuList.value
		  .filter((its:any) => its.state == "2")
		  .every((its:any) => its.select == true);
			select.value =selectAll?true:false
			
		if (!operation.value) {
			mnavTo("/pages/others/completedDettial/completedDettial?invoicing="+item.state+"&needInvoiceId="+item.need_invoice_id)
		}
	}

	const showPop = (source : string) => {
		switch (source) {
			case 'popupEmil':
				popupEmil.value?.open('center')
				break;
			case 'propTime':
				propTime.value?.open('bottom');
				break;
			default:
				break;
		}
	}
	const hidePop = (source : string) => {
		switch (source) {
			case 'popupEmil':
				popupEmil.value?.close()
				break;
			case 'propTime':
				propTime.value?.close()
				break;
			default:
				break;
		}
	}

	const tabSelect = (item : any, index : any) => {
		nowChangeState.value = item.orderState
		operation.value=false
		tabCur.value=index
		loadList('refeash')
	}
	const refresherrefresh = () => {
		refLoad.value = true
		setTimeout(() => {
			refLoad.value = false
		}, 500)
		loadList('refeash')
	}
	const scrolltolower = () => {
		loadList('add')
	}
	const allSecle = () => {	
  let hasSelecId = menuList.value.some((item:any) => item.state == "2");
		if(!hasSelecId){
			return
		}
		select.value = !select.value
		for (const item of menuList.value) {
			item.state == 2 ? item.select = select.value : ''
		}
	}

	const operationFn = () => {
		operation.value = !operation.value
	}
	const sendtoEmail=()=>{
	   let selectNums=0
		for (let item of menuList.value) {
			if(item.select){
				 selectNums+=1
			}
		}
		if(selectNums>0){
			showPop('popupEmil')
		}else{
			mApi.msg("您还未选择!")
		}

	}
	const submitSend=async()=>{
		if(popupEmilvalue.value==''){
			mApi.msg("请输入邮箱!")
			return
		}
		let reg=/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
		let allEmail=reg.test(popupEmilvalue.value)
		if(!allEmail){
			mApi.msg("请输入正确邮箱格式!")
			return
		}
		let resulr=[]
		for (let item of menuList.value) {
			if(item.select){
				 item.mail=popupEmilvalue.value
				 resulr.push(item)
			}
		}
		try{
			let res=await batchInvoice({invoiceNeed:resulr})
			 if(!res.result){
				mApi.msg(res.shortMessage)
				return
			 }
			 mApi.msg("操作成功!")
			 hidePop('popupEmil')
		}catch(e){
			//TODO handle the exception
			mApi.msg("网络异常")
		}
		
		
	}
</script>

<style lang="scss">
	page {
		background-color: #F5F7F6;
	}

	.cuIcon-round {
		color: #999;
	}

	.cuIcon-roundcheckfill {
		color: $base-color;
	}

	.invoice-con {
		width: 700rpx;
		margin: 0 auto;
	}

	.operationActive {
		color: #999 !important;
	}

	.operationActiveBg {
		background-color: #9EC8B4 !important;
	}

	.prompt {
		padding: 20rpx 0;
		margin-top: 60rpx;
		color: #999;
		font-feature-settings: 'clig' off, 'liga' off;
		font-family: "Microsoft YaHei UI";
		font-size: 28rpx;
		font-style: normal;
		font-weight: 400;
		line-height: 150%;
		/* 21px */
	}

	.invoice-li-flex {
		border-radius: 10px;
		padding: 32rpx;
		background: #FFF;
		margin-bottom: 30rpx;

		.invoice-li-right {
			flex: 1;
			transition: all .5s;
		}

		.invoice-li-left {
			margin-right: 20rpx;
		}

		.invoice-li-li {
			margin-bottom: 30rpx;

			.invoice-log-bg {
				background-color: #419B60;
				width: 40rpx;
				height: 40rpx;
				border-radius: 50%;
				margin-right: 14rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.color-style {
				color: #fff;
				font-size: 28rpx;
			}
		}

		.invoice-li-li-font {
			color: #333;
			font-family: "Microsoft YaHei UI";
			font-size: 32rpx;
			font-style: normal;
			font-weight: 400;
			line-height: normal;
		}

		.invoice-li-btm-font {
			color: #999;
			font-family: "Microsoft YaHei UI";
			font-size: 28rpx;
			font-style: normal;
			font-weight: 400;
			line-height: normal;
		}

		.invoice-li-btm-fontWei {
			font-weight: 700;
			color: #333;
		}
	}

	.invoice-footer {
		width: 100%;
		position: fixed;
		bottom: 0;
		background-color: #fff;
		height: 164rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 26rpx;

		.f-font-stylecon {
			margin-left: 10rpx;
		}

		.f-font-style3 {
			color: #333;
			font-family: "Microsoft YaHei UI";
			font-size: 18px;
			font-style: normal;
			font-weight: 700;
			line-height: normal;
		}

		.f-font-style {
			color: #999;
			font-feature-settings: 'clig' off, 'liga' off;
			font-family: "Microsoft YaHei UI";
			font-size: 14px;
			font-style: normal;
			font-weight: 400;
			line-height: 150%;
			/* 21px */
		}

		.footer-right {
			width: 243rpx;
			height: 90rpx;
			flex-shrink: 0;
			border-radius: 10rpx;
			background: #53A87F;
			color: #fff;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

	.popup-content {
		background-color: #fff;
		border-radius: 16rpx;
		width: 530rpx;
		padding-bottom: 40rpx;
		flex-shrink: 0;

		.uni-dialogCon {
			.belivery-title {
				color: #000;
				font-family: "Microsoft YaHei UI";
				font-size: 18px;
				font-style: normal;
				font-weight: 400;
				line-height: normal;
				display: flex;
				justify-content: center;
				padding: 30rpx 0;
			}

			.popupEmil-btn {
				width: 440rpx;
				margin: 0 auto;
				padding-top: 40rpx;

				view {
					width: 202rpx;
					height: 80rpx;
					flex-shrink: 0;
					border-radius: 5px;
					border: 1px solid #5DB175;
					background-color: #fff;
					display: flex;
					justify-content: center;
					align-items: center;
					color: #5DB175;
					font-family: ABeeZee;
					font-size: 32rpx;
					font-style: normal;
					font-weight: 400;
					line-height: normal;

					&:nth-child(2) {
						background-color: #5DB175;
						color: #fff;
					}
				}
			}

			.popupEmil-input {
				width: 440rpx;
				flex-shrink: 0;
				border-radius: 6px;
				background: #F6F7F9;
				margin: 0 auto;

				.popupEmilInput {
					color: #999;
					font-family: "Microsoft YaHei UI";
					font-size: 28rpx;
					font-style: normal;
					font-weight: 400;
					line-height: normal;
					letter-spacing: 0.28px;
				}

				input {
					height: 102rpx;
					line-height: 102rpx;
					padding-left: 20rpx;
				}
			}
		}
	}

	// 选择时间
	.propTime {
		width: 100% !important;
		border-radius: 16rpx 16rpx 0 0;

		.belivery-title-time {
			padding: 40rpx 60rpx;
			color: #333;
			font-family: "Microsoft YaHei UI";
			font-size: 40rpx;
			font-style: normal;
			font-weight: 700;
			line-height: normal;
		}

		.popupTime-btn {
			padding: 0 40rpx;

			view {
				width: 300rpx;
				padding: 32rpx 64rpx;
				flex-shrink: 0;
				border-radius: 43px;
				background: #E7EAE8;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #666;
				text-align: center;
				font-family: "Microsoft YaHei UI";
				font-size: 32rpx;
				font-style: normal;
				font-weight: 400;
				line-height: normal;

				&:nth-child(2) {
					background-color: #53A87F;
					color: #fff;
				}
			}
		}
	}

	.inv-list {
		width: 100%;
		height: calc(100vh - 180rpx);
		position: relative;
	}
	.tipss{
		color: #999;
		font-size: 24rpx;
		font-weight: 400;
		margin:20rpx 0rpx 0 50rpx;
	}
</style>